import { Component, OnInit } from '@angular/core';
import { Alldatas, TreeMap } from 'src/app/service/interface/types';

@Component({
  selector: 'app-proto-tree',
  templateUrl: './proto-tree.component.html',
  styleUrls: ['./proto-tree.component.scss']
})
export class ProtoTreeComponent implements OnInit {

  nodes = [
    {
      title: 'parent 1',
      key: '100',
      expanded: false,
      icon: 'smile',
      children: [
        {
          title: 'leaf',
          key: '1001',
          icon: 'meh',
          expanded: true,
          children: [
            { title: 'leaf', key: '1001', icon: 'meh', isLeaf: true },
            { title: 'leaf', key: '1002', icon: 'frown', isLeaf: true }
          ]
        },
        {
          title: 'leaf',
          key: '1002',
          icon: 'frown',
          isLeaf: true
        }
      ]
    }
  ];

  protoData: string[] = [];
  Alldata: Alldatas[] = [];
  dataList: string[] = [];

  data = `adjust_config {
        ustor:0.6
        ch_condition {
          ch_condi哈哈 {
            group_ids:36252379
            group_ids: 36252374 adgroup_ids: 36好好红红红
          }
          group_ids:36252379
          group_ids: 36252374
          group_ids: 362523这个90}
      }
      adjust_config {
        adjustor:0.6
        ch_condition {
          group_ids:36252379
          group_ids: 36252374
          group_ids: 36252390}
      }
  `

  constructor() { }

  ngOnInit(): void {

  }

  consoleLog() {
    console.log('tree');
    this.processData(this.data)
  }

  nzEvent(event: any) {
    console.log('event', event);

  }
  // 处理字符串data  
  processData(strData: string): void {
    this.dataList = this.splitList(strData)
    const { allData, check } = this.JudgmentLevel(this.dataList)
    this.mapAllData(allData)

    console.log('this.protoData', this.protoData, check);
  }

  // 1.根据换行符将字符串分割为数组 splitList
  splitList(strData: string): string[] {

    const regSpace = /((\s?)+:(\s?)+)/g;       //匹配冒号前后空格
    const regSpace2 = /((\s?)+{)/g;        //匹配左花括号前空格
    const regLastSpace = /^(\s?)+|(\s?)+$/g;  //匹配每行前后空格
    const regSplit = /[(\r\n\s)\r\n\s]+/;    //匹配所有换行和空格

    const replaceSpaceData = strData.replace(regSpace, ":");
    const replaceSpaceData2 = replaceSpaceData.replace(regSpace2, "{");
    const clearSpaceData = replaceSpaceData2.replace(regLastSpace, "");
    const dataList = clearSpaceData.split(regSplit);
    console.log(clearSpaceData, dataList);

    return dataList;
  }

  //判断children和parent的层级
  JudgmentLevel(dataList: string[]) {

    const JudgeList = dataList;

    let ID: number = 1;
    let pId: number = 0
    let levelId: number = 1;
    let stack: string[] = [];
    let stackPid: number[] = [];
    let check: boolean = true;
    let allData: Alldatas[] = []

    JudgeList.forEach((item, index, arr) => {

      //去除每个元素中的空格
      item.trim()

      if (item.indexOf(":") === -1 && item !== "{" && item !== "}") {
        if (!stackPid.length) {
          pId = 0
        }
        stackPid.push(ID) //遇到父，先记录父的ID
        let parent = {
          id: ID,
          name: item,
          level: levelId,
          isParent: true,
          pid: pId
        };
        if (item.indexOf("{") !== -1) {
          parent.name = item.replace(/\{/g, "");
          stack.push("{");
          levelId += 1;
        }
        allData.push(parent);
        pId = ID; //把pId更新为自己的id
        ID++;

      }

      if (item === "{") {
        levelId += 1;
        stack.push("{");
      }

      if (item.indexOf(":") !== -1) { //有冒号:的是children

        let children = {
          id: ID,
          name: item,
          level: levelId,
          isParent: false,
          pid: pId
        }
        if (item.indexOf("}") !== -1) {      //如果包含"}",lastchild = {id:ID,name:item.name} lastchildList.push(lastchild)
          children.name = item.replace(/\}/g, "");
          stack.pop();
          levelId -= 1;
          stackPid.pop()
          pId = Number(stackPid.slice(-1))               //遇到右括号，pId回退                   
        }
        allData.push(children);
        ID++;

      }

      if (item === "}") {    //last = {id:ID-1,name:} lastList.push(lastchild)
        stack.pop();
        levelId -= 1
        stackPid.pop()
        pId = Number(stackPid.slice(-1))               //遇到右括号，pId回退 
      }
    })

    if (stack.length) {
      check = false;
    }

    console.log('Alldata', allData);
    return { allData, check }
  }

  //映射allData
  mapAllData(allData: Alldatas[]) {

    let treeMapList = allData.reduce((memo, current) => {
      memo[current["id"]] = current
      return memo
    }, {} as TreeMap)

    let result = allData.reduce((arr, current) => {
      let pid = current.pid as number
      let parent = treeMapList[pid]
      if (parent) {
        parent.children ? parent.children.push(current) : parent.children = [current]
      } else if (pid === 0) {
        arr.push(current)
      }
      return arr;
    }, [] as Alldatas[])

    console.log('treeMapList', treeMapList);
    console.log('result', result);
    return result;

  }

  /*
    处理data:
       1.根据换行符将字符串分割为数组 dataList ❀完成
       2.遍历dataList:
            判断children和parent的层级：
                  1.依次添加item进栈stack,
                  2.如果item不包含冒号就是父级 给item添加属性:
                  3.let parent = {id:"",name:"",levelId:"",isParent:true,child:[]} 
                  4.let children = {id:"",name:"",levelId:"",isParent:false,child:[]}
                  5.新建一个treeMapList对象 let pid = 0 let ID = 0
                       treeMapList[item] = parent (item要去除所有空格和花括号换行符等)
                       treeMapList[item].levelId = pid name = item id = ID ID++
                       遇到第一个左花括号时,pid++
                    继续 -- item包含冒号时  
                       treeMapList[item] = children (item要去除所有空格和花括号换行符等)
                          treeMapList[item].levelId = pid
                  6.遇到下一个左括号时，重复上面动作
                  7.遇到右花括号时，pid--
  */

  /**
    数组拼接回字符串并加上括号：
       treeMapList.reduce((arr,cur) =>{
         if(是父){
          cur.forst = {id:cur.id,name:cur.name+'{'}
          arr.push(cur)
         }else if(是last){
          cur.last.name = cur.last.name ? cur.last.name:cur.name+'}'
          arr.push(cur)
         }
       },[])
   */


}
